package com.open.cinema.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtil {
    private static final Logger log = Logger.getLogger(IpUtil.class);

    /**
     * 淘宝API：http://ip.taobao.com/service/getIpInfo.php?ip=
     * 新浪API：http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=
     * 百度API：http://api.map.baidu.com/location/ip?ip=
     */

    //调用淘宝的接口
    public static final String IP_Address = "http://ip.taobao.com/service/getIpInfo.php?ip=";


    public static String getIp()
    {
        return getSubjct().getSession().getHost();
    }

    public static Subject getSubjct()
    {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取客户端IP
     */
    public static final String getHost(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("127.0.0.1".equals(ip)) {
            InetAddress inet = null;
            try { // 根据网卡取本机配置的IP
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ip = inet.getHostAddress();
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 根据Ip获取实际地址
     * @param ip
     * @return
     */
    public static String getRealAddressByIP(String ip)
    {
        String address = "未知";
        String rspStr = HttpUtil.httpClientPost(IP_Address + ip);
        if (StringUtils.isEmpty(rspStr))
        {
            log.error("获取地理位置异常 {}");
            return address;
        }
        JSONObject obj;
        try
        {
            obj = JSON.parseObject(rspStr, JSONObject.class);
            JSONObject data = obj.getJSONObject("data");
            String region = data.getString("region");
            String city = data.getString("city");
            address = region + " " + city;
        }
        catch (Exception e)
        {
            log.error("获取地理位置异常 {}");
        }
        return address;
    }

}
